//
//  OrderDetailViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/10/28.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

class OrderDetailViewController: UIViewController {

    var orderVM: OrderViewModel?        
    
    let disposeBag = DisposeBag()
    
    var order: UserOrderDetail?
    
    var scrollView: UIScrollView?
    
//    var mainRole: RoleInOrder?    
    
    var role: [RoleInOrder]?
    
    var showPayment = false //是否到能展示支付凭证的阶段
    
    var showCashBack = false //是否到能展示返現詳情的階段
    
    var canEdit = false //经理人不能编辑订单
    
    let orderNumber: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "ORDER_NUMBER")
        bar.valueLabel.text = LanguageHelper.getString(key: "NO_RESULT")
        bar.pointerLabel.alpha = 0
        return bar
    }()
    
    let orderStatus: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "ORDER_STATUS")
        bar.valueLabel.text = LanguageHelper.getString(key: "NO_RESULT")
        bar.pointerLabel.alpha = 0
        return bar
    }()
    
    let banquetHall: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "FEAST_HALL")
        bar.valueLabel.text = LanguageHelper.getString(key: "NO_RESULT")
        bar.pointerLabel.alpha = 0
        return bar
    }()
    
    let tables: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "FEAST_TABLE")
        bar.valueLabel.text = LanguageHelper.getString(key: "NO_RESULT")
        bar.pointerLabel.alpha = 0
        return bar
    }()
    
    let contact: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "CONTACTMAN")
        bar.valueLabel.text = LanguageHelper.getString(key: "NO_RESULT")
        bar.pointerLabel.alpha = 0
        return bar
    }()
    
    let phone: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "PHONE")
        bar.valueLabel.text = LanguageHelper.getString(key: "NO_RESULT")
        bar.pointerLabel.alpha = 0
        return bar
    }()
    
    let candidateDates: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "CAN_DATE")
        bar.valueLabel.text = LanguageHelper.getString(key: "SEE")
        return bar
    }()
    
    let feastingDate: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "FEAST_DATE")
        bar.valueLabel.text = LanguageHelper.getString(key: "SETTING")
        return bar
    }()
    
    let recommender: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "RECOMMENDER")
        bar.valueLabel.text = LanguageHelper.getString(key: "SETTING")
        return bar
    }()
    
    let manager: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "MANAGER")
        bar.valueLabel.text = LanguageHelper.getString(key: "SETTING")
        return bar
    }()
    
    let contract: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "CONTRACT")
        bar.valueLabel.text = ""
        return bar
    }()
    
    let payment: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "PAYMENT")
        bar.valueLabel.text = ""
        return bar
    }()
    
    let cashBack: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "CASHBACK_DETAIL")
        bar.valueLabel.text = ""
        return bar
    }()
    
    var cdView: UIView?
    
    var barNeedToAdjust: [OrderInfoBar] = []
    
    var cdExpanded: Bool = false
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = lightSaperatorColor
        
        self.navigationItem.title = order?.hotel
        
        checkStatus()
        
        setBackBarItem()
        
        if order?.orderStatus == "TO_BE_REVIEWD" && canEdit {
            let rightBt = UIButton()
            rightBt.contentHorizontalAlignment = .right
            rightBt.setTitle(LanguageHelper.getString(key: "GIVE_REVIEW"), for: .normal)
            rightBt.setTitleColor(doneItemButtonColor, for: .normal)
            rightBt.addTarget(self, action: #selector(submit(_:)), for: .touchUpInside)
            rightBt.sizeToFit()
            self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBt)
        }
        scrollView = UIScrollView()
        scrollView?.backgroundColor = lightSaperatorColor
        scrollView?.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
        scrollView?.showsVerticalScrollIndicator = false
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.isScrollEnabled = true
        scrollView?.alwaysBounceVertical = true
        scrollView?.autoresizingMask = UIViewAutoresizing.flexibleHeight
        
        orderNumber.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: menuHeight)
        orderStatus.frame = CGRect(x: 0, y: menuHeight, width: self.view.bounds.width, height: menuHeight)
        banquetHall.frame = CGRect(x: 0, y: menuHeight * 2, width: self.view.bounds.width, height: menuHeight)
        tables.frame = CGRect(x: 0, y: menuHeight * 3, width: self.view.bounds.width, height: menuHeight)
        contact.frame = CGRect(x: 0, y: menuHeight * 4, width: self.view.bounds.width, height: menuHeight)
        phone.frame = CGRect(x: 0, y: menuHeight * 5, width: self.view.bounds.width, height: menuHeight)
        candidateDates.frame = CGRect(x: 0, y: menuHeight * 6, width: self.view.bounds.width, height: menuHeight)
        feastingDate.frame = CGRect(x: 0, y: menuHeight * 7, width: self.view.bounds.width, height: menuHeight)
        recommender.frame = CGRect(x: 0, y: menuHeight * 8, width: self.view.bounds.width, height: menuHeight)
        manager.frame = CGRect(x: 0, y: menuHeight * 9, width: self.view.bounds.width, height: menuHeight)
        contract.frame = CGRect(x: 0, y: menuHeight * 10, width: self.view.bounds.width, height: menuHeight)
        payment.frame = CGRect(x: 0, y: menuHeight * 11, width: self.view.bounds.width, height: menuHeight)
        cashBack.frame = CGRect(x: 0, y: menuHeight * 12, width: self.view.bounds.width, height: menuHeight)
        
        initOrderValue()
        
        self.scrollView?.addSubview(orderNumber)
        self.scrollView?.addSubview(orderStatus)
        self.scrollView?.addSubview(banquetHall)
        self.scrollView?.addSubview(tables)
        self.scrollView?.addSubview(contact)
        self.scrollView?.addSubview(phone)
        self.scrollView?.addSubview(candidateDates)
        self.scrollView?.addSubview(feastingDate)
        self.scrollView?.addSubview(recommender)
        self.scrollView?.addSubview(manager)
        self.scrollView?.addSubview(contract)
        self.scrollView?.addSubview(payment)
        self.scrollView?.addSubview(cashBack)
        
        if canEdit { //只有消费者能编辑订单
            let fdTapGR = UITapGestureRecognizer()
            fdTapGR.addTarget(self, action: #selector(tapFeastingDate(_:)))
            feastingDate.addGestureRecognizer(fdTapGR)
        
            let reTapGR = UITapGestureRecognizer()
            reTapGR.addTarget(self, action: #selector(tapRecommender(_:)))
            recommender.addGestureRecognizer(reTapGR)
        
            let maTapGR = UITapGestureRecognizer()
            maTapGR.addTarget(self, action: #selector(tapManager(_:)))
            manager.addGestureRecognizer(maTapGR)
        }
        
        let cdTapGR = UITapGestureRecognizer()
        cdTapGR.addTarget(self, action: #selector(tapCandidateDates(_:)))
        candidateDates.addGestureRecognizer(cdTapGR)
        
        let conTapGR = UITapGestureRecognizer()
        conTapGR.addTarget(self, action: #selector(tapContract(_:)))
        contract.addGestureRecognizer(conTapGR)
        
        let payTapGR = UITapGestureRecognizer()
        payTapGR.addTarget(self, action: #selector(tapPayment(_:)))
        payment.addGestureRecognizer(payTapGR)
        
        let cbTapGR = UITapGestureRecognizer()
        cbTapGR.addTarget(self, action: #selector(tapCashback(_:)))
        cashBack.addGestureRecognizer(cbTapGR)
        
        barNeedToAdjust += [feastingDate, recommender, manager, contract, payment]
        
        scrollView?.contentSize = CGSize(width: self.view.bounds.width, height: cashBack.frame.origin.y + cashBack.frame.height)
        self.view.addSubview(scrollView!)
        
        initVM()
    }
    
    func submit(_ sender: UIBarButtonItem) {
        let ratingView = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "RatingViewController") as! RatingViewController
            ratingView.orderVM = self.orderVM
            ratingView.orderId = self.order?.id
        self.navigationController?.pushViewController(ratingView, animated: true)
    }
    
    func initVM() {
        let authManager = AuthManager.share
        if authManager.hasLogined() {
            if let token = authManager.getToken() as? String {
                orderVM = OrderViewModel(token: token)
            }
        }
    }
    
    func checkStatus() {
        if let status = self.order?.orderStatus {
            if orderSteps[status]! > 1 && orderSteps[status]! < 7 {
                showPayment = true
            }
            if orderSteps[status]! > 3 && orderSteps[status]! < 7 {
                showCashBack = true
            }
        }
        if let role = role {
            if role.contains(.customer) {
                canEdit = true
            }
        }
    }
    
    func tapCandidateDates (_ sender: UIGestureRecognizer) {
        if cdExpanded {
            //收起
            UIView.animate(withDuration: 0.5, animations: { [unowned self] in
                self.candidateDates.valueLabel.text = LanguageHelper.getString(key: "SEE")
                self.candidateDates.pointerLabel.transform = CGAffineTransform.identity
                if let cv = self.cdView {
                    cv.removeFromSuperview()
                    let cvHeight = cv.frame.height
                    for bta in self.barNeedToAdjust {
                        let y = bta.frame.origin.y
                        bta.frame = CGRect(x: 0, y: y - cvHeight, width: self.view.bounds.width, height: menuHeight)
                    }
                    let contentSize = (self.scrollView?.contentSize)!
                    self.scrollView?.contentSize = CGSize(width: contentSize.width, height: contentSize.height - cvHeight)
                }
                }, completion: nil)
        } else {
            //展開
            UIView.animate(withDuration: 0.5, animations: { [unowned self] in
                self.candidateDates.valueLabel.text = LanguageHelper.getString(key: "FOLD")
                self.candidateDates.pointerLabel.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)
                if let cv = self.cdView {
                    let cvHeight = cv.frame.height
                    let contentSize = (self.scrollView?.contentSize)!
                    self.scrollView?.contentSize = CGSize(width: contentSize.width, height: contentSize.height + cvHeight)
                    for bta in self.barNeedToAdjust {
                        let y = bta.frame.origin.y
                        bta.frame = CGRect(x: 0, y: y + cvHeight, width: self.view.bounds.width, height: menuHeight)
                    }
                    self.scrollView?.addSubview(cv)
                }
                }, completion: nil)
        }
        cdExpanded = !cdExpanded
    }
    
    func tapFeastingDate (_ sender: UIGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.feastingDate.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.feastingDate.backgroundColor = UIColor.white
                let editPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "OrderEditViewController") as! OrderEditViewController
                editPage.order = self.order
                editPage.editType = .feastingDate
                editPage.completion = { [unowned self] in
                    self.orderVM?.getOrderDetail(id: (self.order?.id)!).subscribe(onNext: { order in
                        self.order = order                        
                        self.initOrderValue()
                    })
                        .addDisposableTo(self.disposeBag)
                }
                self.navigationController?.pushViewController(editPage, animated: true)
        })
    }
    
    func tapRecommender (_ sender: UIGestureRecognizer) {
        if order?.recommender == nil {
            UIView.animate(withDuration: 0.3, animations: { [unowned self] in
                self.recommender.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
                }, completion: { [unowned self] bool in
                    self.recommender.backgroundColor = UIColor.white
                    let editPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "OrderEditViewController") as! OrderEditViewController
                    editPage.order = self.order
                    editPage.editType = .recommender
                    editPage.completion = { [unowned self] in
                        self.orderVM?.getOrderDetail(id: (self.order?.id)!).subscribe(onNext: { order in
                            self.order = order
                            self.initOrderValue()
                        })
                            .addDisposableTo(self.disposeBag)
                    }
                    self.navigationController?.pushViewController(editPage, animated: true)
            })
        }
    }
    
    func tapManager (_ sender: UIGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.manager.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.manager.backgroundColor = UIColor.white
                let editPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "OrderEditViewController") as! OrderEditViewController
                editPage.order = self.order
                editPage.editType = .manager
                editPage.completion = { [unowned self] in
                    self.orderVM?.getOrderDetail(id: (self.order?.id)!).subscribe(onNext: { order in
                        self.order = order
                        self.initOrderValue()
                    })
                    .addDisposableTo(self.disposeBag)
                }
                self.navigationController?.pushViewController(editPage, animated: true)
        })
    }
    
    func tapContract(_ sender: UIGestureRecognizer) {
        if order?.feastingDate == nil || order?.manager == nil {
            self.showPromptView(message: LanguageHelper.getString(key: "FILL_FEASTDATE_MANAGER"), confirmText: LanguageHelper.getString(key: "OK"))
            return
        }
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.contract.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.contract.backgroundColor = UIColor.white
                let filePage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "OrderFileViewController") as! OrderFileViewController
                filePage.order = self.order
                filePage.fileType = .contract
                filePage.canEdit = self.canEdit
                filePage.completion = { [unowned self] in
                    self.orderVM?.getOrderDetail(id: (self.order?.id)!).subscribe(onNext: { order in
                        self.order = order
                        self.initOrderValue()
                    })
                    .addDisposableTo(self.disposeBag)
                }
                self.navigationController?.pushViewController(filePage, animated: true)
        })
    }
    
    func tapPayment(_ sender: UIGestureRecognizer) {
        if showPayment {
            UIView.animate(withDuration: 0.3, animations: { [unowned self] in
                self.payment.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
                }, completion: { [unowned self] bool in
                    self.payment.backgroundColor = UIColor.white
                    let filePage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "OrderFileViewController") as! OrderFileViewController
                    filePage.order = self.order
                    filePage.fileType = .payment
                    filePage.canEdit = self.canEdit
                    filePage.completion = { [unowned self] in
                        self.orderVM?.getOrderDetail(id: (self.order?.id)!).subscribe(onNext: { order in
                            self.order = order
                            self.initOrderValue()
                        })
                        .addDisposableTo(self.disposeBag)
                    }
                    self.navigationController?.pushViewController(filePage, animated: true)
            })
        } else {
            self.showPromptView(message: LanguageHelper.getString(key: "PAYMENT_AFTER_RESERVED"), confirmText: LanguageHelper.getString(key: "OK"))
        }
    }
    
    func tapCashback(_ sender: UIGestureRecognizer) {
        if showCashBack {
            UIView.animate(withDuration: 0.3, animations: { [unowned self] in
                self.cashBack.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
                }, completion: { [unowned self] bool in
                    self.cashBack.backgroundColor = UIColor.white
                    let cashBackPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "OrderCashBackViewController") as! OrderCashBackViewController
                    cashBackPage.orderId = self.order?.id
                    cashBackPage.role = self.role
                    self.navigationController?.pushViewController(cashBackPage, animated: true)
            })
        } else {
            self.showPromptView(message: LanguageHelper.getString(key: "CASHBACK_AFTER_PAYMENT"), confirmText: LanguageHelper.getString(key: "OK"))
        }
    }
    
    func initOrderValue() {
        if let order = order {
            if let on = order.orderNumber {
                orderNumber.valueLabel.text = "\(on)"
            }
            if let status = order.orderStatus {
                let index = orderSteps[status]! - 1
                orderStatus.valueLabel.text = stepNames[index]
            }
            if let bh = order.banquetHall {
                banquetHall.valueLabel.text = bh
            }
            if let ts = order.tables {
                tables.valueLabel.text = "\(ts)"
            }
            if let cont = order.contact {
                contact.valueLabel.text = cont
            }
            if let ph = order.phone {
                phone.valueLabel.text = ph
            }
            if let fd = order.feastingDate {
                feastingDate.valueLabel.text = fd
                feastingDate.layoutSubviews()
            }
            if let reco = order.recommender {
                recommender.valueLabel.text = reco
            }
            if let man = order.manager {
                manager.valueLabel.text = man
                manager.layoutSubviews()
            }
            if let cd = order.candidateDates {
                if cd.count > 0 {
                    let cdHeight: CGFloat = 20
                    cdView = UIView()
                    cdView?.frame = CGRect(x: 0, y: menuHeight * 7, width: self.view.bounds.width, height: CGFloat(cd.count) * cdHeight)
                    for i in 0...cd.count - 1 {
                        let dateLabel = UILabel()
                        dateLabel.font = AppFont(size: 13)
                        dateLabel.textColor = UIColor.gray
                        dateLabel.text = cd[i]
                        let textMaxSize = CGSize(width: self.view.bounds.width, height: cdHeight)
                        let dateSize = TextSize.textSize(text: dateLabel.text!, font: dateLabel.font, maxSize: textMaxSize)
                        dateLabel.frame = CGRect(x: self.view.bounds.width - dateSize.width - 15, y: (cdHeight - dateSize.height) / 2 + CGFloat(i) * cdHeight, width: dateSize.width, height: dateSize.height)
                        cdView?.addSubview(dateLabel)
                    }
                }
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
